import {router,addRoutes} from '@/router/index.js'
import {getToken} from "@/composables/auth.js";
import {toast,showFullLoading,hideFullLoading} from "@/composables/utils.js";
import {useUserInfoStore} from "@/stores/userInfo.js";


let hasGetInfo = false;
router.beforeEach( (to, from, next)=>  {

    showFullLoading()
    //显示loading
    // console.log("全局路由守卫")
    const store = useUserInfoStore()
    const token = getToken();

    //没有登录，强制跳转回登录页
    if (!token && to.path !== '/login') {
        toast("请先登录",'error')
        return next({path:'/login'})
    }

    //防止重复登录
    if(token && to.path === "/login") {
        return next({path:from.path ? from.path : '/home'})
    }

    let hasNewRoutes = false;
    // 如果用户登录了，自动获取用户信息，并且存储在pinia中
    if(token && !hasGetInfo){
        store.getUserInfo()
        store.getMenus()
        let res = store.getMenus()
        hasGetInfo = true;
        res.then(result=>{
            console.log(result)
            //动态添加路由
            hasNewRoutes = addRoutes(result.detail)
        }).catch(error=>{console.log(error)})



    }

    let title = (to.meta.title ? to.meta.title : '') + "-教师管理系统"
    document.title = title

    // next()
    hasNewRoutes ? next(to.fullPath) : next()
})

router.afterEach( (to, from, next)=> {hideFullLoading()})